package com.gjb6.master.app;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.gjb6.master.R;
import com.gjb6.master.account.Account;
import com.gjb6.master.account.AccountManager;
import com.gjb6.master.account.Login.LoginActivity;
import com.gjb6.master.common.web.CommonWebviewFragment;
import com.gjb6.master.common.web.cache.NativeWebService;
import com.gjb6.master.utils.ProviderUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.util.NetUtils;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.picture.picker.utils.FileManager;
import com.pachong.android.frameworkbase.dialog.AlertDialogFragment;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.SLog;
import com.pachong.android.frameworkbase.utils.io.FileUtil;
import com.pachong.android.frameworkbase.utils.zip.ZipExtractor;

import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends BaseActivity {
    public static final int REQ_CODE_READ_LOCATION = 0X003;
    private double latitude;
    private double longitude;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    private static boolean isExit = false;
    private CommonWebviewFragment mWebviewFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initMap();
        hideToolbar();
        String mUrl = "http://engineer.nsfkj.com/#/index";
        mWebviewFragment = CommonWebviewFragment.newInstance(mUrl);
        getSupportFragmentManager().beginTransaction().add(R.id.flytWebview, mWebviewFragment).commit();

        /**
         * 将h5页面本地化
         */
       NativeWebService.requestCacheUrl(this);

        checkPermission();
     /*   TokenInfo info = new TokenInfo();
        info.setExpiresAt("");
        info.setAccessToken("AF318BE799982C97457092AEDA03CE4818724A13D80CF940E75D8AD2E24FB88ABD3165327F97AABB");
        info.setRefreshToken("AF318BE799982C97AECD790497EA6F4CD76F46F2ADECB9A9562CBD088F3E8D02E7A2A6D1E1419C0D");
        info.setServerTime("2016-07-21T14:43:41.080+0800");
        info.setMacKey("qjBDKRD6yJ");

        String url = "http://120.76.200.15:8888/uc/user";
        String authStr = Authorization.createAuthorization(info, url, "get");
        Log.e("vivi", "  auth string === " + authStr);*/


//        testGetAppAttrs();

        String path = FileManager.getWebCachePath(this) + "zygote_web_cache.zip";
        String toPath = FileManager.getWebCachePath(this) + "zygote_web_cache";
        FileUtil.copyAssetToSDCard(getAssets(), "www/zygote_web_cache.zip", path);


        ZipExtractor zipExtractor = new ZipExtractor(this,
                path, toPath,
                new ZipExtractor.OnExtractListener() {
                    @Override
                    public void onProgressUpdate(long currSize) {
                        SLog.e("onProgressUpdate currSize == " + currSize);
                    }
                    @Override
                    public void onComplete(long totalSize) {
                        SLog.e("onComplete totalSize == " + totalSize);
                    }

                    @Override
                    public void onFailure(int errorCode, long totalSize,
                                          long currSize) {
//                        SLog.e("onFailure errorCode == " + errorCode + "totalSize" + totalSize);
                    }

                    @Override
                    public void onCaculateTotalSize(long totalSize) {
                        SLog.e("onCaculateTotalSize totalSize == " + totalSize);
                    }

                });
        zipExtractor.execute();
    }

    private void initMap() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplication());
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(1000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //启动定位
        mLocationClient.startLocation();

    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {

            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    latitude = amapLocation.getLatitude();
                    longitude = amapLocation.getLongitude();
                    String s = longitude + "," + latitude;
                    Log.e("sssss",s);
                    AccountManager.getCurrentAccount().setLongitude(s);
                    mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
                    mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
                    //可在其中解析amapLocation获取相应内容。
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
//                    EasyToast.showToast(MySplashActivity.this, amapLocation.getErrorInfo());
                }
            }
        }
    };

    private void checkPermission() {
        final int apiLevel = Build.VERSION.SDK_INT;
        if(apiLevel>=23){//判断6.0以上的手机
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        REQ_CODE_READ_LOCATION);
            }
        } else {
        }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQ_CODE_READ_LOCATION){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
            } else {
                // Permission Denied
                //  displayFrameworkBugMessageAndExit();
                Toast.makeText(this, "请在应用管理中打开“定位”访问权限！", Toast.LENGTH_LONG).show();
                showPermissionsDialog();
            }
        }
    }

    private void showPermissionsDialog() {

        AlertDialogFragment permissDialogFrag = new AlertDialogFragment();
        permissDialogFrag.setMessage("您未允许获得定位权限，您可在系统设置中开启")
                .setNegativeButton("暂不", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        permissDialogFrag.dismiss();
                    }
                })
                .setPositiveButton("去设置", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ProviderUtils.showInstalledAppDetails(MainActivity.this,"com.gjb6.master");
                        permissDialogFrag.dismiss();
                    }
                })
                .show(getSupportFragmentManager());
    }

    @Override
    protected void onResume() {
        super.onResume();
        //注册一个监听连接状态的listener
        EMClient.getInstance().addConnectionListener(mConnectionListenerclass);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().removeConnectionListener(mConnectionListenerclass);
    }

    public static void start(Activity activity){
        Intent intent = new Intent(activity, MainActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public View createDataView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
        return layoutInflater.inflate(R.layout.activity_main, null);
    }


    void testGetAppAttrs() {
//        TypedArray typedArray1 = obtainStyledAttributes(R.styleable.IconTextArrowButton);
        TypedArray typedArray1 = obtainStyledAttributes(null,R.styleable.BadgeRadioButton,R.attr.badgeRadioButtonStyle,0);
        float drawHeight = typedArray1.getDimension(R.styleable.BadgeRadioButton_drawableHeight, -1.0f);
        Log.e("vivi", "   textSize  ==  " + drawHeight);
        typedArray1.recycle();

        TypedArray typedArray = obtainStyledAttributes(R.styleable.vidroid);
        float textSize1 = typedArray.getDimension(R.styleable.vidroid_textSize1, -1.0f);
        Log.e("vivi", "   textSize1  ==  " + textSize1);
        typedArray.recycle();
    }


    /**
     * 登录环信
     */
    public static void loginHuanxin(final Activity context) {
        Account acct = AccountManager.getCurrentAccount();
        if (acct != null && !TextUtils.isEmpty(acct.getPhone()) && !TextUtils.isEmpty(acct.getPassWord())) {
            Log.e("yy", "  acct getPhone  " + acct.getPhone() + "  pwd " + acct.getPassWord());
//            Log.e("yy", "  acct getUserId  " + acct.getUserId());
            EMClient.getInstance().login(acct.getPhone()+"_hxname", acct.getPhone()+"_hxname", new EMCallBack() {//回调
                @Override
                public void onSuccess() {
                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();
                    Account acct = AccountManager.getCurrentAccount();
//                    UserIconMap map = new UserIconMap();
//                    map.setAvatar(acct.getPortrait());
//                    map.setUserName(acct.getPhone());
//                    map.setNickName(acct.getNickName());
//                    UserIconHelper.setUserIcon(context, map);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            EasyToast.showToast(context, "登录聊天服务器成功！");
                        }
                    });

                    Log.d("main", "登录聊天服务器成功！");
                }
                @Override
                public void onProgress(int progress, String status) {
                }
                @Override
                public void onError(int code, String message) {

                    if(message.equals("User is already login")){
                        EasyToast.showToast(context, "登录聊天服务器失败！您的账号已在别的设备登录");
                }
//                    Log.d("main", "登录聊天服务器失败！code = " + code);
//                    Log.d("main", "登录聊天服务器失败！message = " + message);
                }
            });
        }
    }


    int reconnectTimes = 0;
    //实现ConnectionListener接口
    private EMConnectionListener mConnectionListenerclass = new EMConnectionListener() {
        @Override
        public void onConnected() {
            reconnectTimes = 0;
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (error == EMError.USER_REMOVED) {
                        // 显示帐号已经被移除
                        EasyToast.showToast(MainActivity.this, "帐号已经被移除");
                    } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登录
                        EasyToast.showToast(MainActivity.this, "帐号在其他设备登录");
                        showOutDialog();

                    } else {
                        if (NetUtils.hasNetwork(MainActivity.this)) {
                            //连接不到聊天服务器
//                            EasyToast.showToast(MainActivity.this, "连接不到聊天服务器，正在重新连接！！");
                            // delay to reconnect
                            View view = new View(MainActivity.this);
                            //重新连接不超过3次
                            if (reconnectTimes < 3) {
                                view.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        loginHuanxin(MainActivity.this);
                                        reconnectTimes++;
                                    }
                                }, 6000);
                            }

                        } else {
                            //当前网络不可用，请检查网络设置
                            EasyToast.showToast(MainActivity.this, "当前网络不可用，请检查网络设置");
                        }

                    }
                }
            });
        }
    };

    private void showOutDialog() {
        AlertDialogFragment outDialogFrag = new AlertDialogFragment();
        outDialogFrag.setTitle("温馨提示")
                .setMessage("您的账号在异地登录")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        outDialogFrag.dismiss();
                        //环信退出登录
                        AccountManager.getTokenInfo().clear();
                        EMClient.getInstance().logout(true);
                        LoginActivity.start(MainActivity.this);
                    }
                })
                .show(getSupportFragmentManager());
                 outDialogFrag.setCanceledOnTouchOutside(false);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(!isExit) {
                isExit = true;
                Toast.makeText(this, "在按一次退出程序", Toast.LENGTH_SHORT).show();
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        isExit = false;
                    }
                }, 2000);
            } else {
                Intent startMain = new Intent(Intent.ACTION_MAIN);
                startMain.addCategory(Intent.CATEGORY_HOME);
                startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(startMain);
                System.exit(0);//退出程序
//                           finish();
            }
        }
        return false;
    }

}
